<?php
include 'include.php';

$conexao = new Conexao();

define('PROJECT_NAME', 'Sharethismap, share places');
define('SERVER_PATH', 'http://' . $_SERVER['SERVER_NAME'] . '/maps/');

$menu = array();

function print_user($id, $nome, $foto, $seguir = false, $tam = 1, $lista = false){
    
    $nome = trim($nome);
    $float = '';
    
    if(!$lista){ $float = 'print_user_seq'; }
    
    ?><div class="print_user <?=$float?>"><?
    
    if($seguir)
    {
	?>
	    <div title="<?=$nome?>" class="perfil-seguir">
		<img class="foto-usuario-tam<?=$tam?>" src="./usuarios/fotos/<?=$foto?>" alt="<?=$nome?>" title="<?=$nome?>" />
		<span><?=$nome?></span>
		<a href='javascript:void(0)' onclick='addSeguido(<?=$id?>, true)' class="botao-verde">seguir</a>
	    </div>	    	    	
	<?
    }
    else
    {
	?>
	    <a href="perfil-<?=$id?>" title="<?=$nome?>">
		<img class="foto-usuario-tam<?=$tam?>" src="./usuarios/fotos/<?=$foto?>" alt="<?=$nome?>" title="<?=$nome?>" />
	    </a>
	<?   
    }
    
    ?></div><?

}

function pre($array){
    echo "<pre>";
    print_r($array);
    echo "</pre>";
}

function insereBusca($busca, $id_usuario){
    
    $SQL = "";
    
    if($id_usuario == 0)
	$SQL = "INSERT INTO busca (busca, date) VALUES ('$busca', NOW())";    
    else
	$SQL = "INSERT INTO busca (busca, date, id_usuario) VALUES ('$busca', NOW(), $id_usuario)";    
    
    mysql_query($SQL);
}

function alreadyLoggedIn(){
    if($_SESSION['usuario']['logado']){
	header("Location: home");
    }
}

function checkLogin($login, $senha){
    
    $query = "SELECT * FROM usuario u WHERE u.login = '$login' AND u.senha = '$senha'";
    $result = mysql_query($query);
    
    if($usuario = mysql_fetch_array($result)){

	$_SESSION['usuario'] = $usuario;
	
	$id_usuario = $usuario["id"];
	
	$query = "SELECT idPosicao, lat, lng, zoom FROM posicao p WHERE p.id_usuario = '$id_usuario' AND inicial = 1";
	$result = mysql_query($query);
	
	if(mysql_num_rows($result) == 0){
	    $_SESSION['usuario']['posicaoInicial']['idPosicao'] = 0;	    
	    $_SESSION['usuario']['posicaoInicial']['lat'] = -22.950944078667128;	    
	    $_SESSION['usuario']['posicaoInicial']['lng'] = -43.18862902539058;
	    $_SESSION['usuario']['posicaoInicial']['zoom'] = 13;
	}else{
	    $_SESSION['usuario']['posicaoInicial'] = mysql_fetch_array($result);
	}
	
	$_SESSION['usuario']['logado'] = true;
	return true;
	
    }else
	return false;
    
}

function logout(){
    $_SESSION['usuario']['logado'] = false;
    unset ($_SESSION['usuario']);
}

function checkLogado(){
    if(!$_SESSION['usuario']['logado'])
	header ('Location: index.php');
}

function addUser ($arr){
    
    extract($arr);
    
    $query = "SELECT * FROM usuario WHERE login = '$login' ";
    
	if(mysql_num_rows(mysql_query($query)) > 0)
		return false;

    include('include/php/uploadhelper.php');
	
	$query = "INSERT INTO usuario (login, nome, senha, foto) VALUES ('$login','$nome','$senha', 'semfoto.jpg')";
	mysql_query($query);
	
    $names = uploadHelper::getVar('names');
    $files = uploadHelper::getVar('file_names');
	
	if($names && $files)
	{	
		$source = uploadHelper::decrypt($files[0]);
		
		$type = explode(".", $names[0]);
		$type = $type[count($type)-1];
		
		$id_usuario = mysql_result(mysql_query("SELECT id FROM usuario ORDER BY id DESC LIMIT 1"), 0, 'id');
		
		$nomeFoto = "foto$id_usuario.$type";
		$destiny = "usuarios/fotos/$nomeFoto";
		
		if(copy($source, $destiny)){
			$SQL_foto = "UPDATE usuario SET foto = '$nomeFoto' WHERE id = $id_usuario";
			mysql_query($SQL_foto);
		}	
	}
	
    return true;

}

function geraTabela($title, $SQL){
    $result = mysql_query($SQL);
    ?>
    <h2><?=$title?></h2>
    <table border="1">
	<tr>
    <?
    while($field =  mysql_fetch_field($result)){
	if($field->name != "id"){
	?>
	    <th><?=ucwords( str_replace("_", " ", $field->name) ) ;?></th>
	<?
	}
	
    }
    ?>
	</tr>
    <?    
    while ($row = mysql_fetch_array($result)) {
	?>
	<tr>
	<?
	foreach ($row as $key => $value ) {
	    if(is_numeric($key) && $key > 0){
		?>
		<td><?=$value?></td>
		<?
	    }
	}
	?>
	</tr>
	<?
    }
    ?>
    </table>
    <? 
    
}

function isSeguido($id_seguidor,$id_seguido){
    
    $query = "SELECT * FROM seguidores WHERE id_seguidor = $id_seguidor AND id_seguido = $id_seguido";
    $result = mysql_query($query);
    return (mysql_num_rows($result) > 0 );    
}

function getDadosPerfil($id_perfil){
    
    $query = "SELECT nome as perfil_nome, foto as perfil_foto FROM usuario WHERE id = $id_perfil";
    $result = mysql_query($query);
    
    $retorno = mysql_fetch_array($result);
    
    if(empty($retorno['perfil_foto'])){
	$retorno['perfil_foto'] = "semfoto.jpg";
    }
    
    return $retorno;    
}

function getDadosEditar($id_perfil){
    $query = "
		SELECT
		  i.id , nome as interesse, id_interesse
		FROM
		    interesses i
		    LEFT JOIN (SELECT * FROM meusinteresses m WHERE id_usuario = $id_perfil) mi
		    ON mi.id_interesse = i.id
		ORDER BY 
		    interesse ASC
	    ";
    
    $result = mysql_query($query);
    
    $retorno['interesses'] = $result;
    
    $query = "SELECT *, day(nascimento) as dia, month(nascimento) as mes, year(nascimento) as ano FROM usuario WHERE id = $id_perfil";
    $result = mysql_query($query);
    
    $retorno['dados'] = mysql_fetch_array($result);
    
    return $retorno;
    
}

function getDadosBullet($id){
    $retorno = array();
    
    $query = "
		SELECT
		  *, (SELECT nome FROM usuario u WHERE u.id = o.id_usuario ) as nome , (SELECT foto FROM usuario u WHERE u.id = o.id_usuario ) as foto
		FROM
		  ofertas o
		WHERE
		  id = $id;";
    
    $result = mysql_query($query);
    $retorno['bullet']['info'] = mysql_fetch_array($result);
    
    $query = "
		SELECT
		  r.id as id_relevancia, opt, nome, u.id, u.foto
		FROM
		  relevancias r , usuario u
		WHERE
		  id_mapa = $id AND
		  u.id = r.id_usuario AND
		  opt = 1
		ORDER BY 
		    r.id DESC		
		LIMIT 10 ;";
    
    $result = mysql_query($query);
    $retorno['bullet']['relevancia']['curtidas'] = $result;
    
    $query = "
		SELECT
		  r.id as id_relevancia, opt, nome, u.id, u.foto
		FROM
		  relevancias r , usuario u
		WHERE
		  id_mapa = $id AND
		  u.id = r.id_usuario AND
		  opt = 0
		ORDER BY 
		    r.id DESC
		LIMIT 10;";
    
    $result = mysql_query($query);
    $retorno['bullet']['relevancia']['naoCurtidas'] = $result;
   
    $query = "
		SELECT
		  path
		FROM
		  foto f
		  WHERE
		id_oferta = $id;";
    
    $result = mysql_query($query);
    $retorno['bullet']['fotos'] = $result;
    
    return $retorno['bullet'];
    
}

function getComentarios($id){
    
     $query = "
		SELECT
		  c.*, u.nome, u.foto
		FROM
		  comentarios c, usuario u
		WHERE
		   c.id_autor = u.id AND
		   c.id_oferta = $id
		ORDER BY 
		    data ASC";
          
     $result = mysql_query($query);
     return $result;
     
}

function addComentario($comentario, $id_autor, $id_oferta){
    
    // $comentario = utf8_encode($comentario);
    
    $query = "INSERT INTO comentarios VALUES (default, $id_autor, $id_oferta, '$comentario', now())";
    
    mysql_query($query);
    
}

function echoErro($erro){    
    if(!empty($erro))
	echo "<small class='erro'>$erro</small><br />";
}

function getHomeUsuarios(){
    $query = "SELECT id,nome,foto, (SELECT COUNT(*) FROM usuario) as total  FROM usuario
    ORDER BY RAND()
    LIMIT 22";
    $result = mysql_query($query);
    return $result;
}

?>
